from skimage import data, io
import numpy as np
from scipy.fftpack import fft,ifft
import matplotlib.pyplot as plt
from matplotlib.pylab import mpl
import matplotlib.animation as ani 
mpl.rcParams['font.sans-serif'] = ['SimHei']   #显示中文
mpl.rcParams['axes.unicode_minus']=False       #显示负号

# 动画更新方法
def update(i):
    # img1 = 255 - img1 # 反色开关
    max_t = max1 * m[i]
    fft_img1[ fft_img1 > max_t ] = 0
    fft_img1[ fft_img1 < -max_t ] = 0
    ifft_img1 = ifft(fft_img1)
    img1 = np.short(ifft_img1.T)
    # img1 = 255 - img1 # 反色开关
    img1.shape = img_shape
    plt.title(tle[i])
    img2 = img1
    # img2[(img2[:,:,0] > 10) & (img2[:,:,1] > 10) & (img2[:,:,2] > 10)] = 255
    img2[img2 > 10] = 255
    print(img2.shape)
    return plt.imshow(img2, animated=True),

# 获取猫猫图片
img = io.imread("1.jpg")
# 保存图片形状
img_shape = img.shape
# 一维化三个通道
img.shape = -1, 3
# 转置方便变换
img = img.T
fft_img1 = fft(img)
# 逆变换
ifft_img1 = ifft(fft_img1)
# 再转置回去，顺便把转回的数字转成0-256的整型
img1 = np.short(ifft_img1.T)
# 把三个通道再次二维化为原来的形状
img1.shape = img_shape
max1 = np.abs(fft_img1).max()
m = [0.1, 0.08, 0.05, 0.04, 0.03, 0.02, 0.01, 0.005, 0.001, 0.0005, 0.0001, 0.00001, 0.000001, 0]
tle = [*map(lambda x:f"{x*100:.2f}%", m)] # 标题根据比值自动生成
print(tle)
# tle = ['10%','8%','5%','4%', '3%', '2%', '1%','0.5%','0.1%', '0.05%', '0.01%', '0.001%', '0.0001%', '0%']
fig,ax = plt.subplots()
ani1 = ani.FuncAnimation(fig, update, np.arange(0, len(m)), interval=100, blit=True,repeat=False)
ani1.save('maomao1.gif', writer='imagemagick') # 保存动图
# plt.show()
'''
max_t = max1 * 0.003
fft_img1[ fft_img1 >= max_t ] = 0
fft_img1[ fft_img1 <= -max_t ] = 0
ifft_img1 = ifft(fft_img1)
img1 = np.short(ifft_img1.T)
img1 = 255 - img1
img1.shape = img_shape
plt.title("五光十色的白")
plt.imshow(img1)
plt.show()
'''
''' 下面是从低频开始去除，就是会变得越来越模糊

fft_img1 = fft(img)
ifft_img1 = ifft(fft_img1)
# 再转置回去，顺便把转回的数字转成0-256的整型
img1 = np.short(ifft_img1.T)
# 把三个通道再次二维化为原来的形状
img1.shape = img_shape
m = [0.001, 0.004, 0.008, 0.024, 0.05, 0.1, 0.3, 0.6]
tle = ['原图', '0.1%','0.4%','0.8%','2.4%','5%','10%','30%','60%']
for i in range(7):
    plt.subplot(2,4,i + 1)
    plt.title(tle[i])
    plt.imshow(img1)
    max_t = max1 * m[i]
    fft_img1[ (fft_img1 < max_t) & (fft_img1 > -max_t) ] = 0
    ifft_img1 = ifft(fft_img1)
    img1 = np.short(ifft_img1.T)
    img1.shape = img_shape
plt.subplot(2,4,8)
plt.title(tle[7])
plt.imshow(img1)
plt.show()

''' 
